// DOM元素引用
const promptTextarea = document.getElementById('prompt');
const modelSelect = document.getElementById('model');
const temperatureInput = document.getElementById('temperature');
const maxTokensInput = document.getElementById('max-tokens');
const saveToHistoryCheckbox = document.getElementById('save-to-history');
const clearPromptButton = document.getElementById('clear-prompt');
const generateResponseButton = document.getElementById('generate-response');
const fileDropArea = document.getElementById('file-drop-area');
const fileInput = document.getElementById('file-input');
const fileInfo = document.getElementById('file-info');
const fileName = document.getElementById('file-name');
const removeFileButton = document.getElementById('remove-file');
const uploadFileButton = document.getElementById('upload-file');
const chatFileInput = document.getElementById('chat-file-input');
const selectedFileInfo = document.getElementById('selected-file-info');
const selectedFileName = document.getElementById('selected-file-name');
const removeSelectedFileButton = document.getElementById('remove-selected-file');
const downloadResponseButton = document.getElementById('download-response');
const copyResultButton = document.getElementById('copy-result');
const clearHistoryButton = document.getElementById('clear-history');
const loadingModal = document.getElementById('loading-modal');
const loadingMessage = document.getElementById('loading-message');
const errorModal = document.getElementById('error-modal');
const errorMessage = document.getElementById('error-message');
const closeErrorModal = document.getElementById('close-error-modal');
const successModal = document.getElementById('success-modal');
const successMessage = document.getElementById('success-message');
const closeSuccessModal = document.getElementById('close-success-modal');
const resultContent = document.getElementById('result-content');
const historyList = document.getElementById('history-list');
const mobileMenuButton = document.getElementById('mobile-menu-button');
const mobileMenu = document.getElementById('mobile-menu');
const logoutButton = document.getElementById('logout-button');
const mobileLogoutButton = document.getElementById('mobile-logout-button');

// 禁用下载按钮的函数
function disableDownloadButton() {
    downloadResponseButton.disabled = true;
    downloadResponseButton.classList.add('text-gray-400');
    downloadResponseButton.classList.remove('text-gray-700');
}

// 启用下载按钮的函数
function enableDownloadButton() {
    downloadResponseButton.disabled = false;
    downloadResponseButton.classList.remove('text-gray-400');
    downloadResponseButton.classList.add('text-gray-700');
}

// 移动菜单切换
mobileMenuButton.addEventListener('click', function() {
    mobileMenu.classList.toggle('hidden');
});

// 文件上传处理
fileDropArea.addEventListener('dragover', function(e) {
    e.preventDefault();
    fileDropArea.classList.add('border-pink-500', 'bg-pink-500/5');
});

fileDropArea.addEventListener('dragleave', function() {
    fileDropArea.classList.remove('border-pink-500', 'bg-pink-500/5');
});

fileDropArea.addEventListener('drop', function(e) {
    e.preventDefault();
    fileDropArea.classList.remove('border-primary', 'bg-primary/5');
    
    if (e.dataTransfer.files.length > 0) {
        handleFileSelection(e.dataTransfer.files[0]);
    }
});

fileDropArea.addEventListener('click', function() {
    fileInput.click();
});

fileInput.addEventListener('change', function() {
    if (fileInput.files.length > 0) {
        handleFileSelection(fileInput.files[0]);
    }
});

function handleFileSelection(file) {
    if (!file.name.endsWith('.md')) {
        showErrorMessage('请上传Markdown格式的文件(.md)');
        return;
    }
    
    fileName.textContent = file.name;
    fileInfo.classList.remove('hidden');
}

removeFileButton.addEventListener('click', function() {
    fileInput.value = '';
    fileInfo.classList.add('hidden');
});

// 清空提示按钮
clearPromptButton.addEventListener('click', function() {
    promptTextarea.value = '';
    // 同时清空文件选择
    chatFileInput.value = '';
    selectedFileInfo.classList.add('hidden');
    promptTextarea.focus();
});

// 生成回复按钮
generateResponseButton.addEventListener('click', function() {
    if (chatFileInput.files && chatFileInput.files.length > 0) {
        generateResponseWithFile();
    } else {
        generateResponse();
    }
});

// 聊天区域文件上传处理
chatFileInput.addEventListener('change', function() {
    if (this.files && this.files[0]) {
        const file = this.files[0];
        // 检查文件大小（最大5MB）
        if (file.size > 5 * 1024 * 1024) {
            showErrorMessage('文件大小不能超过5MB');
            this.value = '';
            return;
        }
        
        // 检查文件类型
        const allowedExtensions = ['.txt', '.md', '.json', '.csv', '.html', '.htm', '.xml', '.js', '.css'];
        const fileExtension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
        if (!allowedExtensions.includes(fileExtension)) {
            showErrorMessage('不支持的文件格式，请上传文本类型文件');
            this.value = '';
            return;
        }
        
        selectedFileName.textContent = file.name;
        selectedFileInfo.classList.remove('hidden');
    }
});

// 移除已选择的文件
removeSelectedFileButton.addEventListener('click', function() {
    chatFileInput.value = '';
    selectedFileInfo.classList.add('hidden');
});

// 上传文件按钮
uploadFileButton.addEventListener('click', function() {
    uploadFile();
});

// 下载响应按钮
function handleDownload() {
    if (!downloadResponseButton.disabled) {
        downloadCurrentResponse();
    }
}

downloadResponseButton.addEventListener('click', handleDownload);

// 复制结果按钮
copyResultButton.addEventListener('click', function() {
    copyToClipboard(resultContent.innerText);
    showSuccessMessage('结果已复制到剪贴板');
});

// 清空历史按钮
clearHistoryButton.addEventListener('click', function() {
    if (confirm('确定要清空所有历史记录吗？')) {
        localStorage.removeItem('deepseekHistory');
        renderHistoryList();
        showSuccessMessage('历史记录已清空');
    clearHistoryButton.classList.add('bg-pink-100');
    clearHistoryButton.classList.remove('bg-gray-100');
    }
});

// 模态框关闭按钮
closeErrorModal.addEventListener('click', function() {
    errorModal.classList.add('hidden');
});

closeSuccessModal.addEventListener('click', function() {
    successModal.classList.add('hidden');
});

// 登出处理
function handleLogout() {
    localStorage.removeItem('token');
    localStorage.removeItem('username');
    showSuccessMessage('已登出');
    setTimeout(() => {
        window.location.href = '/login.html';
    }, 1500);
}

// 添加登出事件监听
logoutButton.addEventListener('click', handleLogout);
if (mobileLogoutButton) {
    mobileLogoutButton.addEventListener('click', function() {
        mobileMenu.classList.add('hidden');
        handleLogout();
    });
}

// API 调用函数 - 纯文本生成
function generateResponse() {
    const prompt = promptTextarea.value.trim();
    const model = modelSelect.value;
    const temperature = parseFloat(temperatureInput.value);
    const maxTokens = parseInt(maxTokensInput.value);
    
    if (!prompt) {
        showErrorMessage('请输入提示内容');
        promptTextarea.focus();
        return;
    }
    
    showLoading('正在生成回复...');
    
    // 构建请求参数
    const requestData = {
        prompt: prompt,
        model: model,
        temperature: temperature,
        max_tokens: maxTokens
    };
    
    // 获取JWT令牌
    const token = localStorage.getItem('token');
    
    // 设置请求头
    const headers = {
        'Content-Type': 'application/json'
    };
    
    if (token) {
        headers['Authorization'] = 'Bearer ' + token;
    }
    
    fetch('http://localhost:8000/api/deepseek/generate', {
        method: 'POST',
        headers: headers,
        body: JSON.stringify(requestData)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP 错误! 状态码: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        hideLoading();
        
        if (data.error) {
            showErrorMessage(data.error);
        } else {
            displayResult(data.response);
            
            // 保存到历史记录
            saveToHistory(prompt, data.response);
            
            // 显示复制按钮并启用下载按钮
            copyResultButton.classList.remove('hidden');
            copyResultButton.classList.add('text-pink-600');
            copyResultButton.classList.remove('text-primary');
            enableDownloadButton();
        }
    })
    .catch(error => {
        hideLoading();
        showErrorMessage(`生成回复失败: ${error.message}`);
    });
}

// API 调用函数 - 文件+文本生成
function generateResponseWithFile() {
    const file = chatFileInput.files[0];
    const prompt = promptTextarea.value.trim();
    const model = modelSelect.value;
    const temperature = parseFloat(temperatureInput.value);
    const maxTokens = parseInt(maxTokensInput.value);
    
    if (!file) {
        showErrorMessage('请选择要上传的文件');
        return;
    }
    
    showLoading('正在上传文件并生成回复...');
    
    // 准备表单数据
    const formData = new FormData();
    formData.append('file', file);
    formData.append('prompt', prompt || '');
    formData.append('model', model);
    formData.append('temperature', temperature);
    formData.append('max_tokens', maxTokens);
    
    // 获取JWT令牌
    const token = localStorage.getItem('token');
    
    // 设置请求选项
    const options = {
        method: 'POST',
        body: formData
    };
    
    if (token) {
        options.headers = {
            'Authorization': 'Bearer ' + token
        };
    }
    
    fetch('http://localhost:8000/api/deepseek/upload-file', options)
    .then(response => {
        hideLoading();
        
        if (response.ok) {
            response.json().then(data => {
                if (data.error) {
                    showErrorMessage(data.error);
                } else {
                    displayResult(data.response);
                    
                    // 保存到历史记录
                    saveToHistory(prompt || '文件分析: ' + file.name, data.response);
                    
                    copyResultButton.classList.remove('hidden');
                    enableDownloadButton();
                    
                    // 清空文件选择
                    chatFileInput.value = '';
                    selectedFileInfo.classList.add('hidden');
                }
            });
        } else {
            response.json().then(data => {
                showErrorMessage(data.error || '文件处理失败');
            });
        }
    })
    .catch(error => {
        hideLoading();
        showErrorMessage(`操作失败: ${error.message}`);
    });
}

function uploadFile() {
    const file = fileInput.files[0];
    
    if (!file) {
        showErrorMessage('请先选择一个文件');
        return;
    }
    
    showLoading('正在上传并处理文件...');
    
    const formData = new FormData();
    formData.append('file', file);
    
    // 获取JWT令牌
    const token = localStorage.getItem('token');
    
    // 设置请求选项
    const options = {
        method: 'POST',
        body: formData
    };
    
    if (token) {
        options.headers = {
            'Authorization': 'Bearer ' + token
        };
    }
    
    fetch('http://localhost:8000/api/deepseek/upload', options)
    .then(response => {
        hideLoading();
        
        if (response.ok) {
            response.json().then(data => {
                if (data.error) {
                    showErrorMessage(data.error);
                } else {
                    displayResult(data.response);
                    
                    // 保存文件处理结果到历史记录
                    saveToHistory('文件上传: ' + file.name, data.response);
                    
                    copyResultButton.classList.remove('hidden');
                    enableDownloadButton();
                    showSuccessMessage('文件处理完成');
                }
            });
        } else {
            response.json().then(data => {
                showErrorMessage(data.error || '文件上传失败');
            });
        }
    })
    .catch(error => {
        hideLoading();
        showErrorMessage(`操作失败: ${error.message}`);
    });
}

// 下载当前回复内容为MD文件的函数
function downloadCurrentResponse() {
    const currentContent = resultContent.innerText;
    
    if (!currentContent || currentContent.includes('DeepSeek 助手随时为您服务') || currentContent.includes('生成的结果将显示在这里')) {
        showErrorMessage('没有可下载的内容');
        return;
    }
    
    showLoading('正在准备下载文件...');
    
    // 构建请求参数
    const requestData = {
        prompt: promptTextarea.value.trim() || 'file_upload',
        response: currentContent,
        model: modelSelect.value,
        temperature: parseFloat(temperatureInput.value),
        max_tokens: parseInt(maxTokensInput.value)
    };
    
    // 获取JWT令牌
    const token = localStorage.getItem('token');
    
    // 设置请求头
    const headers = {
        'Content-Type': 'application/json'
    };
    
    if (token) {
        headers['Authorization'] = 'Bearer ' + token;
    }
    
    fetch('http://localhost:8000/api/deepseek/download-response', {
        method: 'POST',
        headers: headers,
        body: JSON.stringify(requestData)
    })
    .then(response => {
        hideLoading();
        
        if (response.ok) {
            const contentDisposition = response.headers.get('content-disposition');
            let fileName = 'deepseek-response.md';
            
            if (contentDisposition) {
                const matches = /filename="([^"]+)"/.exec(contentDisposition);
                if (matches && matches[1]) {
                    fileName = matches[1];
                }
            }
            
            response.blob().then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = fileName;
                document.body.appendChild(a);
                a.click();
                a.remove();
                window.URL.revokeObjectURL(url);
                
                showSuccessMessage('文件已开始下载');
            });
        } else {
            response.json().then(data => {
                showErrorMessage(data.error || '下载失败');
            });
        }
    })
    .catch(error => {
        hideLoading();
        showErrorMessage(`下载失败: ${error.message}`);
    });
}

// 显示结果函数 - 支持基本的 Markdown 渲染
function displayResult(text) {
    // 简单的 Markdown 渲染处理
    let formattedText = text;
    
    // 处理标题（#）
    formattedText = formattedText.replace(/^# (.*$)/gm, '<h1 class="text-xl font-bold mb-2">$1</h1>');
    formattedText = formattedText.replace(/^## (.*$)/gm, '<h2 class="text-lg font-bold mb-1">$1</h2>');
    formattedText = formattedText.replace(/^### (.*$)/gm, '<h3 class="text-base font-bold mb-1">$1</h3>');
    
    // 处理无序列表（-）
    formattedText = formattedText.replace(/^- (.*$)/gm, '<li class="list-disc ml-6">$1</li>');
    
    // 处理有序列表（数字.）
    formattedText = formattedText.replace(/^(\d+)\. (.*$)/gm, '<li class="list-decimal ml-6">$2</li>');
    
    // 处理段落
    formattedText = formattedText.replace(/^(?!<h|<li)(.*$)/gm, '<p class="mb-2">$1</p>');
    
    // 处理代码块（```）
    formattedText = formattedText.replace(/```([\s\S]*?)```/g, function(match, code) {
        return '<div class="bg-gray-100 p-4 rounded-lg my-4 overflow-x-auto"><pre><code>' + code + '</code></pre></div>';
    });
    
    // 处理行内代码（`）
    formattedText = formattedText.replace(/`([^`]+)`/g, '<code class="bg-gray-100 px-1 rounded">$1</code>');
    
    // 处理换行符
    formattedText = formattedText.replace(/\n/g, '');
    
    // 替换多个连续的空段落
    formattedText = formattedText.replace(/<p class="mb-2"><\/p>/g, '');
    
    resultContent.innerHTML = formattedText;
}

// 历史记录相关函数
function saveToHistory(prompt, response) {
    const history = getHistory();
    const timestamp = new Date().toISOString();
    
    history.unshift({
        id: timestamp,
        prompt: prompt,
        response: response,
        date: new Date().toLocaleString()
    });
    
    // 限制历史记录数量（最多保存20条）
    if (history.length > 20) {
        history.pop();
    }
    
    localStorage.setItem('deepseekHistory', JSON.stringify(history));
    renderHistoryList();
}

function getHistory() {
    const historyJson = localStorage.getItem('deepseekHistory');
    return historyJson ? JSON.parse(historyJson) : [];
}

function renderHistoryList() {
    const history = getHistory();
    historyList.innerHTML = '';
    
    if (history.length === 0) {
        const emptyItem = document.createElement('div');
        emptyItem.className = 'text-center text-gray-400 py-6';
        emptyItem.textContent = '暂无历史记录';
        historyList.appendChild(emptyItem);
        return;
    }
    
    history.forEach(item => {
        const historyItem = document.createElement('div');
        historyItem.className = 'p-4 border-b border-gray-100 hover:bg-gray-50 transition-custom cursor-pointer';
        
        // 显示前几行提示内容作为预览
        const promptPreview = item.prompt.substring(0, 100) + (item.prompt.length > 100 ? '...' : '');
        
        historyItem.innerHTML = `
            <div class="text-sm text-gray-500 mb-1">${item.date}</div>
            <div class="text-sm text-gray-700 mb-2">${promptPreview}</div>
            <button class="view-history-item text-primary text-sm hover:underline" data-id="${item.id}">查看详情</button>
        `;
        
        historyList.appendChild(historyItem);
        
        // 添加点击事件
        const viewButton = historyItem.querySelector('.view-history-item');
        viewButton.addEventListener('click', function(e) {
            e.stopPropagation();
            const id = e.target.getAttribute('data-id');
            const historyItem = history.find(item => item.id === id);
            
            if (historyItem) {
                promptTextarea.value = historyItem.prompt;
                displayResult(historyItem.response);
                copyResultButton.classList.remove('hidden');
                enableDownloadButton();
                
                // 滚动到结果区域
                document.getElementById('result').scrollIntoView({ behavior: 'smooth' });
            }
        });
    });
}

// 工具函数
function copyToClipboard(text) {
    const textarea = document.createElement('textarea');
    textarea.value = text;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    document.body.removeChild(textarea);
}

function showLoading(message) {
    loadingMessage.textContent = message;
    loadingModal.classList.remove('hidden');
}

function hideLoading() {
    loadingModal.classList.add('hidden');
}

function showErrorMessage(message) {
    errorMessage.textContent = message;
    errorModal.classList.remove('hidden');
}

function showSuccessMessage(message) {
    successMessage.textContent = message;
    successModal.classList.remove('hidden');
    
    // 2秒后自动关闭成功提示
    setTimeout(function() {
        successModal.classList.add('hidden');
    }, 2000);
}

// 初始化
renderHistoryList();
disableDownloadButton();

// 默认选中保存到历史记录的复选框
saveToHistoryCheckbox.checked = true;

// 平滑滚动处理
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();
        const targetId = this.getAttribute('href');
        const targetElement = document.querySelector(targetId);
        
        if (targetElement) {
            // 关闭移动菜单（如果打开）
            mobileMenu.classList.add('hidden');
            
            // 滚动到目标元素
            targetElement.scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
        }
    });
});

// 响应式处理
function handleResize() {
    if (window.innerWidth >= 768) {
        mobileMenu.classList.add('hidden');
    }
}

window.addEventListener('resize', handleResize);
handleResize();